package com.imooc.config;

import com.imooc.bean.AuthResponse;
import com.imooc.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component("authFilter")
@Slf4j
public class AuthFilter implements GatewayFilter, Ordered {


    private static final String AUTH="Authorization";
    private static final String USERNAME="lhy-user-name";

    @Autowired
    private AuthService authService;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(AUTH);
        String username = headers.getFirst(USERNAME);

        ServerHttpResponse response = exchange.getResponse();

        //没有携带请求头直接响应 401
        if (StringUtils.isBlank(token) || StringUtils.isBlank(username)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //验证失败响应 403
        AuthResponse resp = authService.verify(token, username);
        if (resp.getCode()!=1L){
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }

        //  将用户信息存放在header中传递给下游业务
        ServerHttpRequest.Builder mutate = request.mutate();
        mutate.header(USERNAME,username);
        ServerHttpRequest buildRequest = mutate.build();

        //  如果响应中需要存放数据，也可以放在response的header中
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(USERNAME,username);
        return chain.filter(
                exchange.mutate().request(buildRequest)
                        .response(response).build()
        );
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
